package rabbitmq.ack.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class RabbitTemplateConfig {
    @Resource
    EricConfirmCallBack ericConfirmCallBack;

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        CachingConnectionFactory factory = (CachingConnectionFactory) connectionFactory;
        factory.addConnectionListener(new ConnectionListener() {
            @Override
            public void onCreate(Connection connection) {
                System.err.println("端口：" + connection.getLocalPort());
            }
        });
        RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
        // 指定确认回调为自己
        // 确认 -> rabbitmq 接收到消费者的ack
        // 需要在配置中启用  publisher-confirms
        //如果消息没有到exchange,则ConfirmCallback回调,ack=false,
        //如果消息到达exchange,则ConfirmCallback回调,ack=true
        rabbitTemplate.setConfirmCallback(ericConfirmCallBack);
        // 触发setReturnCallback回调必须设置mandatory=true, 否则Exchange没有找到Queue就会丢弃掉消息, 而不会触发回调
        rabbitTemplate.setMandatory(true);
//        rabbitTemplate.setReturnCallback(new RabbitReturnCallback());
        return rabbitTemplate;
    }
} 
